import cors from '@koa/cors'
import Router from '@koa/router'
import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import logger from 'koa-logger';

export interface NewsItem {
  id?: number
  title: string
  content: string
}

let newsData: NewsItem[] = []
let nextId = 1

function initFakeData() {
  newsData = []
  for (let i = 0; i < 108; i++) {
    newsData.push({
      id: nextId++,
      title: `标题${i + 1}`,
      content: `内容：${i + 1}`,
    })
  }
}

const app = new Koa()
const router = new Router()

app.use(
  cors({
    origin: '*', // 允许任何来源
    credentials: true, // 允许携带凭证
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // 允许的HTTP方法
    allowHeaders: [
      'Content-Type',
      'Authorization',
      'Accept',
      'X-Requested-With',
    ], // 允许的请求头
  })
)
app.use(bodyParser())
app.use(logger())

router.get('/news/list', (ctx) => {
  const { page = 1, pageSize = 10, keyword = '' } = ctx.query

  const pageNum = parseInt(page as string) || 1
  const size = parseInt(pageSize as string) || 10
  const searchKeyword = keyword as string

  const data = [...newsData].reverse()

  // 根据关键字过滤
  let filteredData = data
  if (searchKeyword) {
    filteredData = data.filter(
      (item) =>
        item.title.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        item.content.toLowerCase().includes(searchKeyword.toLowerCase())
    )
  }

  // 分页
  const total = filteredData.length
  const startIndex = (pageNum - 1) * size
  const endIndex = startIndex + size
  const list = filteredData.slice(startIndex, endIndex)

  ctx.body = {
    list,
    total,
  }
})

router.get('/news/detail/:id', (ctx) => {
  const id = parseInt(ctx.params.id)
  const newsItem = newsData.find((item) => item.id === id)

  if (!newsItem) {
    ctx.status = 404
    ctx.body = { error: '新闻不存在' }
    return
  }

  ctx.body = newsItem
})

router.post('/news/create', (ctx) => {
  const { title, content } = (ctx.request as any).body as Omit<NewsItem, 'id'>

  if (!title || !content) {
    ctx.status = 400
    ctx.body = { error: '标题和内容不能为空' }
    return
  }

  const newItem: NewsItem = {
    id: nextId++,
    title,
    content,
  }

  newsData.push(newItem)

  ctx.body = newItem
})

router.put('/news/update/:id', (ctx) => {
  const id = parseInt(ctx.params.id)
  const { title, content } = (ctx.request as any).body as NewsItem

  const index = newsData.findIndex((item) => item.id === id)

  if (index === -1) {
    ctx.status = 404
    ctx.body = { error: '新闻不存在' }
    return
  }

  if (title) {
    newsData[index].title = title
  }
  if (content) {
    newsData[index].content = content
  }

  ctx.body = newsData[index]
})

router.delete('/news/delete/:id', (ctx) => {
  const id = parseInt(ctx.params.id)
  const index = newsData.findIndex((item) => item.id === id)

  if (index === -1) {
    ctx.status = 404
    ctx.body = { error: '新闻不存在' }
    return
  }

  const deletedItem = newsData.splice(index, 1)[0]

  ctx.body = {
    message: '删除成功',
    deletedItem,
  }
})

router.get('/', (ctx) => {
  ctx.body = {
    message: '新闻API服务',
    endpoints: [
      'GET /news/list - 获取新闻列表',
      'GET /news/detail/:id - 获取新闻详情',
      'POST /news/create - 创建新闻',
      'PUT /news/update/:id - 修改新闻',
      'DELETE /news/delete/:id - 删除新闻',
    ],
  }
})

app.use(router.routes())
app.use(router.allowedMethods())

const PORT = process.env.PORT || 3000

app.listen(PORT, () => {
  console.log(`服务器启动在端口 http://localhost:${PORT}`)
  initFakeData()
})

